import React, {PropsWithChildren, useEffect, useState} from "react";
import {AppContext} from '@/types'
import user from '@/store/user';
import account from '@/store/account';
import {ShowToast} from "./utils";
import Taro from "@tarojs/taro";
import "./app.scss";

// 全局conteext
export const AppContextWrapper: React.FC<React.PropsWithChildren> = (props) => {
  const [userInfo, setUserInfo] = useState({})
  return <AppContext.Provider value={{ userInfo, setUserInfo }}>
    {props.children}
  </AppContext.Provider>
}

const toLogin = () => {
  if (Taro) {
    Taro.redirectTo({ url: '/pages/login/index' })
  } else {
    setTimeout(() => {
      toLogin()
    }, 500)
  }
}

const versionCheck = () => {
  if (Taro.canIUse('getUpdateManager')) {
    const updateManager = Taro.getUpdateManager();
    updateManager.onCheckForUpdate(function (res) {
      if (res.hasUpdate) {
        updateManager.onUpdateReady(function () {
          Taro.showModal({
            title: '更新提示',
            showCancel: false,
            confirmText: '马上重启',
            content: '新版本已经上线，需要您重启小程序以应用新版本。',
            success: function (res) {
              if (res.confirm) {
                updateManager.applyUpdate();
              }
            }
          });
        });
        updateManager.onUpdateFailed(function () {
          Taro.showModal({
            title: '更新失败',
            content: '新版本下载失败，请删除当前小程序，重新搜索打开。',
          });
        });
      } else {
        console.log('当前为最新版本')
      }
    });
  } else {
    Taro.showModal({
      title: '提示',
      content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。',
    });
  }
}

const App: React.FC = (props: PropsWithChildren) => {
  
  Taro.useLaunch(() => {
    versionCheck()
  })

  useEffect(() => {
    user.updateInfo().then(() => {
      account.doUpDateAccount()
      // categorys.doUpDateCategorys()
      if (user.info?.identityCheck) {
        user.checkUserAuth("你的账户开启了身份验证功能，请验证后再使用").then(() => {
        }).catch(err => {
          ShowToast(err.msg).then(() => {
            toLogin()
          })
        })
      }
    })
  }, [])
  return (
    <AppContextWrapper>
      {props.children}
    </AppContextWrapper>
  )
}

export default App;
